#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 18/12/2023 下午10:05
# Author: name
# File: login_manage.py
# ide: PyCharm
# description: 登录管理
import time

import jmespath
import requests
from pywebio.output import *
from pywebio.pin import *
from pywebio.session import eval_js

from backend.app.config import HOST
from commons.comms import close_pop
from frontend.menus import show_menus


def business_crud_data(action=None, item_id=None):
    if action == "save":
        login_name = pin.login_name
        login_temp = pin.login_temp
        login_desc = pin.login_desc
        data = {
            "name": login_name,
            "login_temp": login_temp,
            "description": login_desc,
        }
        result = requests.post(HOST + "/login/add", json=data)
        toast(f"{result.json()['name']},新增成功")
    elif action == "update":
        login_name = pin.login_name
        login_temp = pin.login_temp
        login_desc = pin.login_desc
        data = {
            "name": login_name,
            "login_temp": login_temp,
            "description": login_desc,
        }
        result = requests.put(HOST + f"/login/{item_id}", json=data)
        toast(f"{result.json()['name']},更新成功")
    elif action == "delete":
        result = requests.delete(HOST + f"/login/{item_id}")
        toast(result.json()["message"])
        time.sleep(1)
        eval_js("window.location.reload();")
    else:
        pass


def html_update_login_temp(data):
    print(data)
    return popup('模板编辑', [
        put_row([
            put_text("模板名称"),
            put_input("login_name", value=data[1]),
        ], size="20% 70%"),
        put_row([
            put_text("描述信息"),
            put_input("login_desc", value=data[3]),
        ], size="20% 70%"),
        put_row([
            put_text("模板内容")
        ], size="20% 70%"),
        put_row([
            put_textarea("login_temp", rows=30, code={
                'mode': "python",
                'theme': 'darcula'
            }, value=data[2])
        ]),
        put_row([
            None,
            put_button("提交", onclick=lambda: business_crud_data("update", data[0]), small=True),
            put_button('关闭', onclick=lambda: close_pop(), color="secondary", small=True)
        ], size="70% 15%"),

    ], size="large", closable=False)


def html_add_login_temp():
    return popup('模板新增', [
        put_row([
            put_text("模板名称"),
            put_input("login_name"),
        ], size="20% 70%"),
        put_row([
            put_text("描述信息"),
            put_input("login_desc"),
        ], size="20% 70%"),
        put_row([
            put_text("模板内容")
        ], size="20% 70%"),
        put_row([
            put_textarea("login_temp", rows=30, code={
                'mode': "python",
                'theme': 'darcula'
            })
        ]),
        put_row([
            None,
            put_button("提交", onclick=lambda: business_crud_data("save"), small=True),
            put_button('关闭', onclick=lambda: close_pop(), color="secondary", small=True)
        ], size="70% 15%"),

    ], size="large", closable=False)


def get_page_data(page: int = 1, size: int = 5, name: str = None):
    query_param = {
        "page": page,
        "size": size,
        "name": name if name else ""
    }
    response = requests.get(HOST + "/login/page", params=query_param)

    print(response.text)
    variable_json = response.json().get("results")
    total = response.json().get("total")
    search_key = response.json().get("search_key")
    data_list = []
    if variable_json:
        data_list = jmespath.search("[].values(@)", variable_json)
    for v in data_list:
        exec_code = f"""
v[2]=put_collapse(v[1], [v[2]], open=False)
v.append(
    put_row([
        put_button("编辑", onclick=lambda: html_update_login_temp({v}),small=True),
        None,
        put_button("删除", onclick=lambda: business_crud_data("delete",{v[0]}),color="danger",small=True),
    ]
    )
)
    """
        exec(exec_code)
    print(data_list)
    return total, page, search_key, data_list


def business_pages_data(current_page=1, page_size=10, name=None):
    page_size = 10
    print(f"当前第{current_page}页")
    if current_page < 1:
        current_page = 1
        toast("当前第一页")
        return
    total, current_page, search_key, data_list = get_page_data(current_page, page_size, name)
    if total <= page_size:
        total_page = 1
    else:
        total_page = int(total / page_size) + 1
    if current_page > total_page:
        current_page = total_page
        toast("当前最后一页")
        return
    table_header = [
        put_html('<h4 style="width:40px">编号</h4>'),
        put_html('<h4 style="width:200px">登录模板名称</h4>'),
        put_html('<h4 style="width:500px">登录模板内容</h4>'),
        put_html('<h4 style="width:100px">描述信息</h4>'),
        put_html('<h4 style="width:150px">创建时间</h4>'),
        put_html('<h4 style="width:150px">更新时间</h4>'),
        put_html('<h4 style="width:200px">操作</h4>'),
    ]
    with use_scope("data_list", clear=True):
        put_tabs(
            [
                {
                    "title": "登录管理",
                    "content": [
                        put_button("新增", onclick=lambda: html_add_login_temp(), small=True),
                        put_row(
                            [
                                put_text("环境名称: "),
                                put_input(name="env_search", placeholder="请输入环境名称进行查询", value=search_key),
                                None,
                                put_button("搜索",
                                           onclick=lambda: business_pages_data(name=pin.env_search), small=True),
                                put_button("重置",
                                           onclick=lambda: business_pages_data(), small=True),
                            ], size="8% 50% 5% 6%"
                        ),
                        put_table(data_list, header=table_header),
                        put_row([
                            put_text(
                                f"      每页{page_size}条      当前第{current_page}/{total_page}页       总共{total}条"),
                            put_button("上一页",
                                       onclick=lambda: business_pages_data(current_page - 1, page_size), small=True),

                            put_button("下一页",
                                       onclick=lambda: business_pages_data(current_page + 1, page_size), small=True),

                        ], size="40% 6% 6%"
                        )

                    ]
                }
            ], scope="data_list"
        )


def html_login_manage():
    """
    登录管理

    :return:
    """

    show_menus()
    business_pages_data()
